﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Util;

namespace BibleBase
{
    [Serializable]
    class NVIRVEntry
    {
        public int NVINumber { get; set; }
        public string NVIEntry { get; set; }
        public int RVNumber { get; set; }
        public string RVEntry { get; set; }

        public string RVOriginalEntry { get; set; }

        public string NVIOriginalEntry { get; set; }
    }

    [Serializable]
    public class NVIRVEntriesMap : PersistentObject
    {
        List<NVIRVEntry> Entries = new List<NVIRVEntry>();

        Regex rx = new Regex(@"(\(\w{1,3}\))+", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        private string Repl(string text)
        {
            string result = text.Replace(",", "").Replace(" ", "");
            MatchCollection matches = rx.Matches(text);
            if (matches.Count > 0)
                foreach (Match match in matches)
                {
                    foreach (var group in match.Groups)
                    {
                        result = result.Replace(((Group)group).Value, "");
                    }
                }
            return result;
        }

        public void AddXLS1Info(int rvNumber, string rvEntry, string nviEntry)
        {
            string rvEntry1 = Repl(rvEntry);
            string nviEntry1 = Repl(nviEntry);
            if (Entries.Any(x => x.RVNumber == rvNumber)) throw new Exception("Entrada repetida!");
            Entries.Add(new NVIRVEntry { RVNumber = rvNumber, RVEntry = rvEntry1, NVIEntry = nviEntry1, RVOriginalEntry = rvEntry, NVIOriginalEntry = nviEntry });
        }

        public void AddXLS2Info(int nviNumber, string nviEntry)
        {
            string nviEntry1 = Repl(nviEntry);
            NVIRVEntry entry = Entries.FirstOrDefault(x => string.Compare(x.NVIEntry, nviEntry1, true) == 0);
            if (entry == null) throw new Exception("Entrada no encontrada!");
            entry.NVINumber = nviNumber;
        }

        public int RVNumberFromNVINumber(int nviNumber)
        {
            NVIRVEntry entry = Entries.FirstOrDefault(x => x.NVINumber == nviNumber);
            if (entry == null) throw new Exception("Entrada no encontrada!");
            return entry.RVNumber;
        }

        public string RVEntryFromNVINumber(int nviNumber)
        {
            NVIRVEntry entry = Entries.FirstOrDefault(x => x.NVINumber == nviNumber);
            if (entry == null) throw new Exception("Entrada no encontrada!");
            return entry.RVEntry;
        }

        public static string DefaultPath { get { return Config.BinPath + @"\NVIRVEntriesMap.bin"; } }
    }
}
